﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Configuration;
using Company.StudyClub.Model;
using Company.StudyClub.DAL;
using Company.StudyClub.BLL.Site;

namespace Company.StudyClub.BLL.HttpModule
{
    public class AdminModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication application)
        {
            application.AcquireRequestState += (new EventHandler(this.Application_AcquireRequestState));
        }

        private void Application_AcquireRequestState(Object source, EventArgs e)
        {
            HttpApplication objApp = (HttpApplication)source;
            HttpRequest objRequest = objApp.Request;
            HttpResponse objResponse = objApp.Response;

            string type = objRequest["type"];
            if (objRequest.Url.ToString().ToLower().IndexOf("course/create/create.ashx") > -1 && type != null)
            {
                if (type == "uploadscorm" || type == "uploadcovericon")
                return;
            }

            // User Handle
            User_Info objCurrentUser = new User_Info();
            objCurrentUser.UserID = 0;
            if (Cookie.CookieManager.ReadCookie(User.UserConst.COOKIE_SERIALIZE_NAME) != null && Cookie.CookieManager.ReadCookie(User.UserConst.COOKIE_SERIALIZE_NAME).Length != 0)
            {
                string seUser = Cookie.CookieManager.ReadCookie(User.UserConst.COOKIE_SERIALIZE_NAME).Trim();
                try
                {
                    User.UserBLL objBLL = new User.UserBLL();

                    objCurrentUser = objBLL.DeSerialUser(seUser);
                }
                catch { }
            }

            // Dev Mode
            bool devMode = false;
            if (Cookie.CookieManager.ReadCookie(objApp.Context, "DevModeCookie") != null && Cookie.CookieManager.ReadCookie(objApp.Context, "DevModeCookie").Length != 0)
            {
                try { devMode = Boolean.Parse(Cookie.CookieManager.ReadCookie(objApp.Context, "DevModeCookie").Trim()); }
                catch { }
            }
            if (objRequest["Dev"] != null && objRequest["Dev"].Trim().Length > 0)
            {
                try { devMode = Boolean.Parse(objRequest["Dev"].Trim()); }
                catch { }
                Cookie.CookieManager.WriteCookie(objApp.Context, "DevModeCookie", devMode.ToString(), DateTime.Parse("1900-1-1"));
            }

            // Language
            string language = "cs";
            if (Cookie.CookieManager.ReadCookie(objApp.Context, "LanguageCookie") == null || Cookie.CookieManager.ReadCookie(objApp.Context, "LanguageCookie").Length == 0)
            {
                string clientLanguage = objRequest.ServerVariables.Get("HTTP_ACCEPT_LANGUAGE").ToLower();
                if (clientLanguage.IndexOf("zh") >= 0)
                    language = "cs";
                else
                    language = "en";
                Cookie.CookieManager.WriteCookie(objApp.Context, "LanguageCookie", language, DateTime.Parse("1900-1-1"));
            }
            else
            {
                language = Cookie.CookieManager.ReadCookie(objApp.Context, "LanguageCookie").Trim();
            }
            if (objRequest["ln"] != null && objRequest["ln"].Trim().Length > 0)
            {
                try { language = objRequest["ln"].Trim(); }
                catch { }
                Cookie.CookieManager.WriteCookie(objApp.Context, "LanguageCookie", language, DateTime.Parse("1900-1-1"));
            }
            string url = objRequest.ServerVariables["SCRIPT_NAME"].Trim();

            // Area
            string area = Site.AreaLayer.Instance.GetAreaName(url);

            // Setup Enviroment (Just Init Config Related Values)
            Site_Enviroment objE = new Site_Enviroment();
            objE.Area = area;
            objE.DevMode = devMode;
            objE.Language = language;
            objE.ServerName = ConfigurationManager.AppSettings.Get("ServerName");

            if (objCurrentUser.UserID == 0)
            {
                bool needLogin = Site.ConfigLayer.Instance.GetBool("Site.LoginRequired", objE);
                if (needLogin)
                {
                    Cookie.CookieManager.WriteCookie("UnloginUrl", objRequest.Url.ToString(), DateTime.Parse("1900-1-1"));
                    Control objControl = new Control();
                    objResponse.Redirect(objControl.ResolveClientUrl("~/login/login.aspx"));
                    objResponse.End();
                    return;
                }
            }
            else
            {
                FunctionBLL objF = new FunctionBLL();
                int functionId = objF.GetFunctionIDByArea(area);

                if (functionId > 0)
                {
                    string userArea = Cookie.CookieManager.ReadCookie(objApp.Context, "UserAreaList");

                    if (string.IsNullOrEmpty(userArea))
                    {
                        RoleUsersBLL objRU = new RoleUsersBLL();
                        userArea = objRU.GetUserAreaList(objCurrentUser.UserID);

                        Cookie.CookieManager.WriteCookie(objApp.Context, "UserAreaList", Encrypt.EncryptLayer.En(userArea), DateTime.Parse("1900-1-1"));
                    }
                    else
                    {
                        userArea = Encrypt.EncryptLayer.Un(userArea);
                    }

                    if (userArea.ToLower().IndexOf("|" + area.ToLower() + "|") == -1)
                    {
                        objResponse.Redirect("/usererror.aspx?e=functionaccess&area=" + area.ToString());
                        objResponse.End();
                        return;
                    }
                    else
                    {
                        Cookie.CookieManager.WriteCookie(objApp.Context, "CurrentFunctionArea", area, DateTime.Parse("1900-1-1"));
                    }
                }
            }
        }
    }
}

